
// 大文件上传
 function uploadCreate() {
    layui.use('upload', function(){
        var upload = layui.upload;
        var element = layui.element;

        // 自定义切片上传组件
        function ChunkUploader(elemId, progressId, type) {
            this.elemId = elemId;
            this.type = type
            this.progressId = progressId;
            this.chunkSize = 5 * 1024 * 1024; // 每个切片的大小
            this.initUploader();
            this.keyFile = new Set()
            this.loading = null
        }

        ChunkUploader.prototype.initUploader = function() {
            var self = this;
            upload.render({
                elem: '#' + self.elemId,
                url: 'http://10.3.0.64:9900/minio/register',
                accept: 'file',
                size: 4096*1024, //限制文件大小，单位 KB
                auto:false,
                multiple: true, // 是否允许多文件上传
                before:function () {
                    return false
                },
                error: function(e){
                    //请求异常回调
                    layer.msg('文件大小不能超过4GB');
                },
                choose:async function(obj) {
                    // $('#' + self.progressId).show();
                    let files = obj.pushFile()
                    for (const filesKey in files) {
                        if(!self.keyFile.has(filesKey)){
                            self.keyFile.add(filesKey)
                            await progressCrate(self.progressId,`dom${files[filesKey].size}`,files[filesKey].name)
                            if(files[filesKey].size < self.chunkSize) {
                                self.uploadFromData(self.type,files[filesKey])
                            }else {
                                let flag = await self.uploadRepeat(await self.getFileMD5(files[filesKey]),self.type,files[filesKey])
                                console.log(flag === null)
                                if(flag === null) {
                                     self.uploadFile(files[filesKey]);
                                }
                            }


                        }

                    }

                },

            });
        };


        // 文件切片
        ChunkUploader.prototype.uploadFile = async function(file) {
            var self = this;
            var total = Math.ceil(file.size / self.chunkSize); // 分片总数
            var uploadedChunks = []; // 已上传的分片
            var fileName = file.name //文件名字
            var fileMD5 = await self.getFileMD5(file)
            let { data } = await self.searchFileMds(fileMD5) // 根据md5值查询,已经上传的切片数量
            if (data !== null) {
                if(data* 1 === total) {
                    self.mergeChunks(fileMD5,fileName)
                    return
                }
                // 如果已上传的分片数不为 null，说明还有分片未上传
                uploadedChunks = Array.from({ length: data }, (_, i) => i + 1)
            }

            //从下一个分片开始上传
            var start = uploadedChunks.length * self.chunkSize;
            var end = start + self.chunkSize;
            while (start < file.size) {                var chunk = file.slice(start, end);
                self.uploadChunk(chunk, start, end, file.size, total, uploadedChunks,fileName,fileMD5);
                start = end;
                end = start + self.chunkSize;
            }
        };

        // 生成md5
        ChunkUploader.prototype.getFileMD5 =function (file) {
          let userId = localStorage.getItem('userId')
            return new Promise((resolve, reject) => {
                let md5s = md5(`${userId}${file.name}${file.size}`)
                resolve(md5s)
            });
        }

        // 分片上传
        ChunkUploader.prototype.uploadChunk = function(chunk, start, end, totalSize, total, uploadedChunks,fileName,fileMD5) {
            var self = this;
            var formData = new FormData();
            let index = Math.ceil(start / self.chunkSize)
            formData.append('file', chunk);
            formData.append('total', total);
            formData.append('index', index+1);
            formData.append('md5', fileMD5); // 替换为文件的唯一标识

            $.ajax({
                url: 'http://10.3.0.64:9900/minio/uploadChunk',
                type: 'POST',
                dataType: 'json',
                data: formData,
                processData: false,
                contentType: false,
                success: function(res) {
                    uploadedChunks.push(Math.ceil(start / self.chunkSize)); // 记录已上传的分片
                    let num = (( uploadedChunks.length / total) * 100).toFixed()
                    $('#' +`dom${totalSize}`).children().css('width',num + '%')
                    $('#' +`dom${totalSize}`).children().attr('aria-valuenow',num)
                    $('#' +`dom${totalSize}`).children().text(num + '%')
                    if (uploadedChunks.length === total) {
                        // 所有分片都已上传，执行合并切片操作
                        self.mergeChunks(fileMD5,fileName,totalSize); // 替换为文件的唯一标识和文件名称
                    }
                },
                error: function(res) {
                    layer.msg('错误');
                    $('#' +`dom${totalSize}`).remove()
                }
            });
        };

        //合并
        ChunkUploader.prototype.mergeChunks = function(md5,name,size) {
            var self = this;
            const formData = new FormData();
            formData.append('md5', md5.toString());
            formData.append('fileName', name);
            $.ajax({
                url: 'http://10.3.0.64:9900/minio/mergeChunks',
                type: 'POST',
                data: formData,
                processData: false, // 禁止 jQuery 处理数据
                contentType: false, // 禁止 jQuery 设置请求头部
                success:function(res) {

                    // 请求成功时的处理
                    if(res.code === 0) {
                        typeDom(res.data,self.type)
                        $('#' + `dom${size}`).remove()
                        $('#' + `namedom${size}`).remove()
                        return
                    }
                    $('#' + `dom${size}`).remove()
                    $('#' + `namedom${size}`).remove()
                    layer.msg(res.msg);
                },
                error: function(r) {
                    layer.msg(r.msg);
                    $('#' + `dom${size}`).remove()
                    $('#' + `namedom${size}`).remove()
                    // 合并切片失败后的操作
                }
            });
        };

        // 查询md5值，断点续传
        ChunkUploader.prototype.searchFileMds= function(md5) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: `http://10.3.0.64:9900/minio/uploadSchedule?md5=${md5}`,
                    type: 'get',
                    success: function(response) {
                        // 请求成功时的处理
                        if(response.code !== 0) {
                            layer.msg(response.msg);
                            reject(new Error('错误'))
                            return
                        }
                        resolve(response)
                    },
                    error: function(xhr, status, error) {
                        // 请求失败时的处理
                        layer.msg(error);
                        reject(new Error(error))
                    }
                });
            })
        };

        //普通上传
        ChunkUploader.prototype.uploadFromData =function (type,file) {
            var self = this;
            const formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: 'http://10.3.0.64:9900/minio/uploadFile',
                type: 'POST',
                data: formData,
                processData: false, // 禁止 jQuery 处理数据
                contentType: false, // 禁止 jQuery 设置请求头部
                success: function(r) {
                    if(r.code === 0) {
                        $('#' +`dom${file.size}`).children().css('width',100 + '%')
                        $('#' +`dom${file.size}`).children().attr('aria-valuenow',100)
                        $('#' +`dom${file.size}`).children().text(100 + '%')
                        typeDom(r.data,type)
                        $('#' + `dom${file.size}`).remove()
                        $('#' + `namedom${file.size}`).remove()
                        return
                    }
                    $('#' + `dom${file.size}`).remove()
                    $('#' + `namedom${file.size}`).remove()
                    layer.msg(r.msg);
                },
                error: function(r) {
                    $('#' + `dom${file.size}`).remove()
                    $('#' + `namedom${file.size}`).remove()
                    layer.msg(r.msg);
                }
            });
        }

        //查询重复的文件
        ChunkUploader.prototype.uploadRepeat = function (md5,type,file) {

            var self = this;
            return new Promise((resolve, reject) => {
                var formData = new FormData();
                formData.append('md5', md5);
                $.ajax({
                    url: 'http://10.3.0.64:9900/minio/register',
                    type: 'POST',
                    dataType: 'json',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        // layer.close(self.loading); // 关闭loading
                        if(res.code === 0) {
                            if(res.data !== null){
                                $('#' +`dom${file.size}`).children().css('width',100 + '%')
                                $('#' +`dom${file.size}`).children().attr('aria-valuenow',100)
                                $('#' +`dom${file.size}`).children().text(100 + '%')
                                typeDom(res.data,type)
                                $('#' + `dom${file.size}`).remove()
                                $('#' + `namedom${file.size}`).remove()

                            }
                            resolve(res.data)
                        }
                    },
                    error: function(res) {
                        reject(res)
                        $('#' + `dom${file.size}`).remove()
                        $('#' + `namedom${file.size}`).remove()
                    }
                });
            })
        }

        var uploader1 = new ChunkUploader('btnUploadVideo', 'videos-progress-content',3,);
        var uploader2 = new ChunkUploader('btnUploadDocument', 'document-progress-content',2);
        var uploader2 = new ChunkUploader('btnUploadImage', 'imgAll-progress-content',4);
        var uploader2 = new ChunkUploader('btnUploadpackages', 'pagesall-progress-content',1);
        var uploader2 = new ChunkUploader('btnUploadaudio', 'audio-progress-content',5);
    });

}

function progressCrate(doms,filterName,name) {
    let valueDom = `
        <p id="name${filterName}">${name}</p>
        <div id="${filterName}" class="progress">
          <div class="progress-bar progress-bar-striped bg-danger" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
        </div>
    `
    $(`#${doms}`).append(valueDom)

}

// 模板筛选
function typeDom(data,type = type * 1,id ) {
    let value = data.substring(data.lastIndexOf('/') + 1);

    let content = `
		<div class="pagestText">
			<img class="pagesFil" src="/img/close.png" style="position: absolute;top: 1px;right: -15px;">
			<div class="textOverflow" onclick="videoPlayback('${data}','${type}','${id}')" data-name="${data}" style="width: 100%;color: #009688" title="${value}">${value}</div>
		</div>
		`
    let page = `
		<div class="pagestText">
			<img class="pagesFil" src="/img/close.png" style="position: absolute;top: 1px;right: -15px;">
			<a class="textOverflow" style="display: block;color:#009688" data-name="${data}" class="btn-color" href="${data}" title="${value}" >${value}</a>
		</div>
		`
    let imgs= `
			<div class="img-div">
				<div class="drop-left"></div>
					<img class="pagesFil" src="/img/close.png" style="position: absolute;top: -8px;right: 5px;">
					<img class="imgValue" src="${data}" data-name="${data}" draggable="true"/>
				<div class="drop-right"></div>
			</div>
		`
    switch (type) {
        case 1:
            $('#pagesall').append(page)
            closeChange()
            break;
        case 2:
            $('#document').append(content)
            closeChange()
            break;
        case 3:
            $('#videos').append(content)
            closeChange()
            break;
        case 4:
            $('#imgAll').append(imgs)
            closeChange()
            dragoverImg()
            imageCreate()
            break;
        case 5:
            $('#audio').append(content)
            closeChange()
            break;
        default:

            break;
    }
}

//删除
function closeChange() {
    let list =['#pagesall','#document','#videos','#imgAll','#audio']
    for (let i = 0; i < list.length; i++) {
        $(list[i]).on('click', '.pagesFil', function() {
            $(list[i]).prev().find('input').prevObject.val("")
            $(this).closest('.pagestText,.img-div').remove();
        });
    }
}

//图片拖拽事件注册
function dragoverImg() {
    var $srcImgDiv = null

    // 开始拖动
    $(".imgValue").bind("dragstart", function () {
        $srcImgDiv = $(this).parent()
    })

    // 拖动到.drop-left,.drop-right上方时触发的事件
    $(".drop-left,.drop-right").bind("dragover", function (event) {
        // 必须通过event.preventDefault()来设置允许拖放
        event.preventDefault()
    })

    // 结束拖动放开鼠标的事件
    $(".drop-left").bind("drop", function (event) {
        event.preventDefault()
        if ($srcImgDiv[0] != $(this).parent()[0]) {
            $(this).parent().before($srcImgDiv)
        }
    })
    $(".drop-right").bind("drop", function (event) {
        event.preventDefault()
        if ($srcImgDiv[0] != $(this).parent()[0]) {
            $(this).parent().after($srcImgDiv)
        }
    })


}

function Documentexamine(id) {
    $.ajax({
        url: "/couInfo/documentConversion",
        type: "POST",
        data: {
            resourceId: id
        },
        dataType: "json",
        success: function (r) {
            if(r.code=='200'||r.code==200){
                if(r.data.pdfUrl){
                    //http只能进行下载本地临时地址访问
                    $.ajax({
                        url: r.data.pdfUrl,
                        mimeType: 'text/plain; charset=x-user-defined',
                        cache: true,
                        type: "GET",
                        async: false,
                        success: function (data) {
                            var rawLength = data.length;
                            var array = new Uint8Array(new ArrayBuffer(rawLength));
                            for (i = 0; i < rawLength; i++) {
                                array[i] = data.charCodeAt(i) & 0xff;
                            }
                            //上面是把后台请求到的文件流进行转化为符合的流
                            var blob = new Blob([array],{type: 'application/pdf;charset-UTF-8'});
                            let file=window.URL.createObjectURL(blob)
                            layer.open({
                                type: 2,
                                title: '预览',
                                closeBtn: 1,
                                area: [ '800px', '600px' ],
                                fixed: false,
                                maxmin: true,
                                content:file
                            });

                        },
                        error: function (err) {
                            console.log("错误")
                        }
                    });
                }else{
                    layer.msg("请重试")
                }
            }else{
                layer.msg("请保存后，再阅览")
            }
        },
        error: function (err) {
        }
    });
}

//视频播放
function videoPlayback(url,type,id) {
    if(type === '3' || type=== '5') {
        let contens = `
        <div style="width: 500px;height: 300px;margin: 0 auto;margin-top: 65px">
         <video src="${url}" autoplay controls></video>
        </div>
    `
        layer.open({
            type: 1, // 弹框类型，这里是普通的页面层
            title: type === '3' ? '视频' : '音频', // 弹框标题
            content: contens, // 弹框内容，可以是 HTML 代码或 DOM 元素的选择器
            area: ['800px', '500px'], // 弹框的宽高
        });
    } else if (type === '2'){
        Documentexamine(id)
    } else if (type === '1'){
        let a = document.createElement('a')
        a.href = url

    }

}